#ifndef CS270_2016FA_GAMEBOARD_IMPL
#define CS270_2016FA_GAMEBOARD_IMPL
#include "connectfour.h"
#include <algorithm>
#include <iostream>

namespace CS270Game {

//Examine the connect four board and determine if there is a winner
template <class Token>
bool GameBoard<Token>::findLines(Token val, int len) {
  //vertical
  for (int i = 0; i < nrows; i++) {
    //Look for a streak of len non-empty tokens in a row
    int streak = 0;
    for (int j = 0; j < ncols; j++) {
      if (theBoard[i][j] == val) {
        streak++;
      } else {
        streak = 0;
      }
      if (streak == len) {
        return true;
      }
    }
  }

  for (int j = 0; j < ncols; j++) {
    //Look for a horizontal streak
    int streak = 0;
    for (int i = 0; i < nrows; i++) {
      if (theBoard[i][j] == val) {
        streak++;
      } else {
        streak = 0;
      }
      if (streak == len) {
        return true; //Will convert to integer
      }
    }
  }

  //Look for diagonal forward-slash wins
  for (int j = 1-nrows; j < ncols; j++) {
    int istart = std::max(0, -j);
    int streak = 0;
    for (int i = istart; i < nrows && i+j < ncols; i++) {
      if (theBoard[i][i+j] == val) {
        streak++;
      } else {
        streak = 0;
      }
      if (streak == len) {
        return true; //Will convert to integer
      }
    }
  }

  //Look for diagonal backward-slash wins
  for (int j = ncols + nrows - 2; j >= 0; j--) {
    int istart = std::max<int>(0, j - ncols + 1);
    int streak = 0;
    for (int i = istart; i < nrows && j-i >= 0; i++) {
      if (theBoard[i][j-i] == val) {
        streak++;
      } else {
        streak = 0;
      }
      if (streak == len) {
        return true; //Will convert to integer
      }
    }
  }

  //No wins detected, despite our best efforts.
  return false;
}

}
#endif //CS270_2016FA_GAMEBOARD_IMPL
